import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  OnlineSettlementAndSupplyChainFinanceSettlementLoans,
  FinancialTransactionsUsersGetByUsername,
  TransactionsOredrsCreate,
  ApplyPaymentSettlementUpdateIsSettlement,
  ApplyPaymentSettlementUpdateIsDuePayment,
  ApplyPaymentSettlementUpdatePaymentStatus,
  UpdateCommerceEnterpriseToSpv
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
import { emitter } from "@/utils/mitt";
export function useEBusinessPayment() {
  const route = useRoute()
  const dataList = ref<any>([
  ]);
  const loading = ref<boolean>(false);
  const rowData = ref()
  const payTittle = ref()
  const payVisible = ref(false)
  const selectData = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "采购项目名称",
      prop: "purchaseName",
    },
    {
      label: "付款日期",
      prop: "settlementTime",
    },
    {
      label: "结算方式",
      prop: "type",
      cellRenderer: ({ row }) => (
        <span>
          {row.type === 1 ? "在线结算" : "供应链金融结算"}
        </span>
      )
    },
    {
      label: "付款金额（元）",
      prop: "financingAmount",
    },
    {
      label: "操作",
      fixed: "right",
      minWidth: 150,
      slot: "operation"
    }
  ];


  async function getList() {
    const res = await OnlineSettlementAndSupplyChainFinanceSettlementLoans({
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
    });
    if (res.success) {
      res.data.items.forEach(item => {
        item.createTime = item.createTime.substring(0, 10)
        item.settlementTime = item.settlementTime.substring(0, 10)
        item.purchaseName = item.purchaseName.split(";").join(",").replace(/^,/, "");
      })
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }


  onMounted(() => {
    getList()
  })

  function handleSizeChange() {
    getList()
  }
  function handleCurrentChange() {
    getList()
  }
  //点击放款操作

  function handleLender(row) {
    rowData.value = row
  }

  function handlePay(row) {
    selectData.value = row
    payTittle.value = `是否确定支付 ${row.purchaseName}货款${row.financingAmount}元?`
    payVisible.value = true
  }

  async function confirmPay() {
    //电商付款给金融公司自有资金 转账给金融公司 修改当前列表状态为true 把paystatus改为4 后金融公司给供应商付款
    if (selectData.value.type == 1) {
      //直接结算就是直接给钱一起修改状态
      //修改状态
      const data = qs.stringify({
        userName: '电商平台',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      const data1 = qs.stringify({
        userName: '供应商企业',
        taskId: route.query.taskId,
        planId: route.query.planId,
      })
      const [res, res1] = await Promise.all([
        FinancialTransactionsUsersGetByUsername(data),
        FinancialTransactionsUsersGetByUsername(data1)
      ]);
      const fromTransactionsUserId = res.data.transactionsUserId
      const toTransactionsUserId = res1.data.transactionsUserId
      const data2 = {
        fromTransactionsUserId: fromTransactionsUserId,
        toTransactionsUserId: toTransactionsUserId,
        menuId: '',
        amount: selectData.value.financingAmount,
        description: '电商平台支付货款',
        taskId: route.query.taskId,
        planId: route.query.planId,
      }
      let res2 = await TransactionsOredrsCreate(data2)
      if (res2.success) {
        emitter.emit('refreshMoney')
        payVisible.value = false
        const updataStatus = qs.stringify({
          id: selectData.value.applyPaymentSettlementId
        });
        //修改到期付款状态
        let updataRes = await ApplyPaymentSettlementUpdateIsDuePayment(updataStatus);
        if (updataRes) {
          ElMessage.success('结算成功！')
        } else {
          ElMessage.error(updataRes.msg)
        }
        //修改结算单状态
        let updataRes1 = await ApplyPaymentSettlementUpdateIsSettlement(updataStatus)
        //更新当前余额
        getList()
      } else {
        ElMessage.error(res2.msg)
      }
      //转账
    } else {
      const data = qs.stringify({
        userName: '电商平台',
        taskId: route.query.taskId,
        planId: route.query.planId,
      });
      let res = await FinancialTransactionsUsersGetByUsername(data);
      if (Number(res.data.balance == 0)) {
        ElMessage.warning('电商企业的钱包余额为0元，请先充值！！！')
        return
      }
      const fromTransactionsUserId = res.data.transactionsUserId;
      let toTransactionsUserId;
      let routeType;
      if (selectData.value.routeType == 1) {
        routeType = '金融公司';
        const data1 = qs.stringify({
          userName: routeType,
          taskId: route.query.taskId,
          planId: route.query.planId,
        });
        let res1 = await FinancialTransactionsUsersGetByUsername(data1);
        toTransactionsUserId = res1.data.transactionsUserId;
        if (toTransactionsUserId) {
          const data2 = {
            fromTransactionsUserId: fromTransactionsUserId,
            toTransactionsUserId: toTransactionsUserId,
            menuId: '',
            amount: selectData.value.financingAmount,
            description: '电商平台支付货款',
            taskId: route.query.taskId,
            planId: route.query.planId,
          };
          let res2 = await TransactionsOredrsCreate(data2);
          if (res2.success) {
            emitter.emit('refreshMoney');
            payVisible.value = false
            //电商企业结算后 修改融资放款为支付利息
            const data = qs.stringify({
              id: selectData.value.applyPaymentSettlementId,
              status: 4,
            });
            const res = await ApplyPaymentSettlementUpdatePaymentStatus(data);
            const updataStatus = qs.stringify({
              id: selectData.value.applyPaymentSettlementId
            });
            let updataRes = await ApplyPaymentSettlementUpdateIsDuePayment(updataStatus)
            if (updataRes) {
              ElMessage.success('结算成功！')
            } else {
              ElMessage.error(updataRes.msg)
            }
            getList();
          } else {
            ElMessage.error(res2.msg);
          }
        }
      } else if (selectData.value.routeType == 2) {
        const params = qs.stringify({
          type: 1, id: selectData.value.applyPaymentSettlementId, taskId: route.query.taskId, planId: route.query.planId
        })
        let res = await UpdateCommerceEnterpriseToSpv(params)
        if (res.success) {
          emitter.emit('refreshMoney');
          payVisible.value = false
          //电商企业结算后 修改融资放款为支付利息
          const data = qs.stringify({
            id: selectData.value.applyPaymentSettlementId,
            status: 4,
          });
          const res = await ApplyPaymentSettlementUpdatePaymentStatus(data);
          const updataStatus = qs.stringify({
            id: selectData.value.applyPaymentSettlementId
          });
          let updataRes = await ApplyPaymentSettlementUpdateIsDuePayment(updataStatus)
          if (updataRes) {
            ElMessage.success('结算成功！')
          } else {
            ElMessage.error(updataRes.msg)
          }
          getList();
        } else {
          ElMessage.error(res.msg)
        }
      } else {
        ElMessage.warning('请先在金融公司完成融资放款')
      }
    }
  }
  return {
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    rowData,
    handleLender,
    confirmPay,
    handlePay,
    payVisible,
    payTittle,
  }
}

